var form = layui.form,
    id=getQueryVariable("id"),
    selectdata=[],//目录集合json
    productdata=JSON.parse(window.sessionStorage.getItem("productMidifyData")),//被修改的数据对象
    cataId=window.sessionStorage.getItem('cataId'),//被点击的目录ID
    cataCodeStr="";//获取的目录编码

//获取所有产品目录
queryAllProductCatalog();
//获取目录编码
queryCatalogByCode();


//目录树
let productTreeList=[];
layer.ready(function () {
    //产品目录
    let treeList=toTree(selectdata);
    if(treeList){
        let productTree = getAllJson(treeList);
        productTreeList=getxmselect("#pid","pid", productTree)
    }else {
        productTreeList=getxmselect("#pid","pid", [])
    }

    if(id!=""){
        $("input[name='code']").attr("readOnly",true);
        $("#name").val(productdata.name);
        $("#code").val(productdata.code);
        $("#remark").val(productdata.remark);
        productTreeList.setValue([ productdata.parentId ]);
    }else {
        $("#code").val(cataCodeStr);
        if (cataId!=null){
            productTreeList.setValue([ cataId ]);
        }
    }

})




//监听提交
form.on('submit(form-element)', function(data){
    if(insert(data.field)){
        layer.msg("保存成功", {icon: 6});
        setTimeout(function () {
            //保存成功则刷新提交过来的界面 并关闭此页面
            parent.detab("views/jsp/BasicData/product.jsp");
            parent.intab("views/jsp/BasicData/product.jsp","产品")
            parent.detab("views/jsp/BasicData/tpl/newupdirectory.jsp"+(id==''?'':'?id='+id));

        },1000)
    }else{
        layer.msg("保存失败", {icon: 6});
    }


    return false;
});

//获取所有产品目录
function queryAllProductCatalog() {
    $.ajax({
        type : 'get',
        url:'productcatalog/queryPid',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                selectdata=da.data;
            }
        }
    });
}

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["id"];
        tmparr["name"]=item["name"];
        if(item["children"]){
            tmparr["children"]=  getAllJson(item["children"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }
    }
    return tmpitem
}
function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        autoRow: true,
        filterable: true,
        radio: true,
        tree: {
            show: true,
            showFolderIcon: true,
            showLine: true,
            indent: 20,
            expandedKeys: [ -3 ],
            strict: false,
        },
        height: '300px',
        data: data,
        on: function(data){
            if(data.isAdd){
                return data.change.slice(0, 1)
            }
        },
    });
}

function  insert(data) {
    if(id !="") data.id=id;
    var tf=false;
    $.ajax({
        type : 'post',
        //  url : 'resource/getTree',
        data:JSON.stringify(data),
        url:'productcatalog/insert',
        dataType:"json",
        contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                tf=da.data==0?false:true;

            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}

//获取目录编码
function queryCatalogByCode() {
    $.ajax({
        type : 'get',
        url:'productcatalog/queryCatalogByCode',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                cataCodeStr=da.data;
            }
        }
    });
}

//json转tree
function toTree(data) {
    let result = []
    if(!Array.isArray(data)) {
        return result
    }
    let map = {};
    data.forEach(item => {
        map[item.id] = item;
    });
    data.forEach(item => {
        let parent = map[item.pid];
        if(parent) {
            (parent.children || (parent.children = [])).push(item);
        } else {
            result.push(item);
        }
    });
    return result;
}
